# -*- encoding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.addons import base_cw
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_round, float_compare


class account_cash_dialy_flows_wizard(models.TransientModel):
    _name = 'account.cash.dialy.flows.wizard'

    period_id = fields.Many2one('account.period', u'期别')
    active_id = fields.Integer(u'master_id')
    active_model = fields.Char(string=u"主档对象名", help=u"由程式转入")
    master_id = fields.Many2one('account.cash.dialy.flows.report', u'报表设定', ondelete="set null")
    date_stop = fields.Date(u'截止日')

    @api.model
    def default_get(self, fields):
        if self._context is None:
            self._context = {}
        res = super(account_cash_dialy_flows_wizard, self).default_get(fields)
        active_id = self._context.get('active_id', False)
        if not active_id:
            return res
        active_model = self._context.get('active_model', False)
        if not active_model:
            return res
        period_id = self._context.get('period_id', False)
        if period_id:
            res.update(period_id=period_id)
            res.update(date_stop=self.env['account.period'].browse(period_id).date_stop)
        res.update(active_model=active_model)
        res.update(active_id=active_id)
        res.update(master_id=active_id)
        return res


    def action_confirm(self):
        self.ensure_one()
        self._cr.execute("""select account_cash_dialy_flows_report_settle(%s,%s,%s) """ % (self.period_id.id, self.active_id, self._uid))

        self.master_id.write(dict(date_stop=self.date_stop,
                                  date_settle=fields.Date.context_today(self),
                                  period_id=self.period_id.id,))

    @api.onchange('period_id')
    def onchange_period_id(self):
        if self.period_id:
            self.date_stop = self.period_id.date_stop


    def wizard_view(self):
        view = self.env.ref('cncw_ledger.view_account_cash_dialy_flows_wizard')
        return {
            'name': _(u'期别选择'),
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'account.cash.dialy.flows.wizard',
            'views': [(view.id, 'form')],
            'view_id': view.id,
            'target': 'new',
            'res_id': self.ids[0],
            'context': self.env.context,
        }
